<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div style="padding:1rem;">
    <form onsubmit="return false;">
      <input type="file" onchange="uploadImage(this);" accept=".jpg,.jpeg,.png,.gif,.webp">
    </form>

    <div style="text-align: center;" id="image-view">
    </div>
  </div>

  <script>
    function uploadImage(t) {
      if (t.files.length == 0) {
        return
      }

      let img = t.files[0]

      let fm = new FormData()

      fm.append('image', img)

      fetch('/upload', {
        method : 'POST',
        mode : 'cors',
        body : fm
      }).then(res => {
        if (res.ok) {
          //只有请求成功才会返回数据
          return res.text()
        } else {
          throw new Error(`status: ${res.status}`)
        }
      }, err => {

      }).then(d => {
        if (d === undefined || d === '') {
          return
        }

        let imgdom = document.getElementById('image-view')

        imgdom.innerHTML = `<img src="/image/${d}" style="max-width:60%;height:auto;">`
      })
      .catch(err => {
        console.log(err)
      })

    }
  </script>
</body>
</html>